package com.note.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.note.common.vo.ResponseVo;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 网关访问过滤器
 * 确保服务只能通过网关访问，不能直接访问
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GatewayOnlyFilter implements Filter {

    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 网关添加的请求头标识
     */
    @Value("${gateway.access.header:X-Gateway-Access}")
    private String gatewayHeader;
    
    /**
     * 网关请求头的值
     */
    @Value("${gateway.access.secret:note-gateway-123456}")
    private String gatewaySecret;
    
    /**
     * 允许直接访问的路径
     */
    @Value("${gateway.access.allowPaths:/k8s-health,/actuator/**,/v3/api-docs/**,/swagger/**,/swagger-ui/**,/doc.html,/webjars/**}")
    private String allowPathsStr;
    
    /**
     * 是否启用网关检查
     */
    @Value("${gateway.access.enabled:true}")
    private boolean enabled;
    
    private List<String> allowPaths;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (allowPathsStr != null && !allowPathsStr.isEmpty()) {
            allowPaths = Arrays.asList(allowPathsStr.split(","));
        } else {
            allowPaths = Collections.emptyList();
        }
        log.info("GatewayOnlyFilter 初始化完成: enabled={}, allowPaths={}", enabled, allowPaths);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        
        // 如果禁用了过滤器，直接放行
        if (!enabled) {
            chain.doFilter(request, response);
            return;
        }
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        
        // 检查是否是允许直接访问的路径
        if (isAllowPath(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 检查是否来自网关
        String gatewayValue = httpRequest.getHeader(gatewayHeader);
        if (gatewaySecret.equals(gatewayValue)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 不是来自网关的请求，拒绝访问
        log.warn("拒绝直接访问服务: path={}, ip={}", requestURI, request.getRemoteAddr());
        rejectAccess((HttpServletResponse) response);
    }
    
    /**
     * 拒绝访问，返回JSON格式的错误信息
     */
    private void rejectAccess(HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        
        ResponseVo<Void> responseVo = ResponseVo.error(
                HttpStatus.FORBIDDEN.value(), 
                "禁止直接访问，请通过API网关访问");
        
        String jsonResponse = objectMapper.writeValueAsString(responseVo);
        response.getWriter().write(jsonResponse);
    }
    
    /**
     * 检查是否是允许直接访问的路径
     */
    private boolean isAllowPath(String requestURI) {
        for (String allowPath : allowPaths) {
            // 支持通配符匹配
            if (allowPath.endsWith("/**")) {
                String prefix = allowPath.substring(0, allowPath.length() - 3);
                if (requestURI.startsWith(prefix)) {
                    return true;
                }
            } else if (requestURI.equals(allowPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        // 不需要特殊操作
    }
} 